/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.smarttmt.idu.web.beans;

import com.smarttmt.idu.web.behavior.Preloadable;
import com.smarttmt.idu.web.persistence.controller.UsuacontJpaController;
import com.smarttmt.idu.web.persistence.entity.Usuacont;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
import org.primefaces.util.StringEncrypter;

/**
 *
 * @author Nicolás Rubén Caballero Ortega (helaman58@gmail.com)
 */
@Named(value = "changePasswordBean")
@SessionScoped
public class ChangePassword extends SmartIduBackingBean implements Serializable, Preloadable {

    private String passwordOld;
    private String password;
    private String reTypePassword;
    @PersistenceUnit(unitName = "smarttmtiduappPU")
    private EntityManagerFactory emf;
    @Resource
    private UserTransaction utx;
    private UsuacontJpaController usuacontJpaController;

    /**
     * Creates a new instance of changePassword
     */
    public ChangePassword() {
    }

    @PostConstruct
    public void postConstructorChangePassword() {
        usuacontJpaController = new UsuacontJpaController(utx, emf);
    }

    @Override
    public void preload(Map<String, Object> parameters) throws Exception {
        resetData();
    }

    public void resetData() {
        this.password = null;
        this.reTypePassword = null;
    }

    public boolean comparePasswordAndReType() {
        return this.password.equalsIgnoreCase(this.reTypePassword);
    }
    
    public void compareOldAndNew(){
        if(this.passwordOld.equalsIgnoreCase(this.password)){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Escoger una nueva contraseña. La anterior y la nueva no pueden ser iguales", "Cambie su nueva contraseña"));
        }
    }
    
    public boolean validatorComparatorOldAndNew(){ 
        compareOldAndNew();
        return !this.passwordOld.equalsIgnoreCase(this.password);
    }  
    

    public boolean changePasswordDB() throws Exception {
        //se implementa lógica para cambiar la contraseña del usuario
        Usuacont usuacont = usuacontJpaController.getUserByUsconomb(getUserLoginBean().getUsername());
        System.out.println(getUserLoginBean().getUsername());
        
        //Se encripta la clave
        StringEncrypter strEnc = new StringEncrypter(password);
        String penc = strEnc.encrypt(password);
        //Se pasa al objeto del registro en la DB  
        //anteriormente se pasaba password, pero ahora se pasa el parámetro encriptado
        usuacont.setUscopass(penc);
        usuacontJpaController.edit(usuacont);
        return true;
    }

    public String changePasswordOperation() {
        if (comparePasswordAndReType() && validatorComparatorOldAndNew()) {
            //rutina para la actulización de contraseña
            try {
                if (changePasswordDB()) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Su clave ha sido cambiada correctamente", "Recuerdelo para su próximo inicio de sesión"));
                    return "inquireChipsRegistred";
                } else {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Su clave no se ha podido cambiar", "Comuníquese con nuestras oficinas"));
                    return null;
                }

            } catch (Exception e) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Su clave no se ha podido cambiar", "Comuníquese con nuestras oficinas"));
                return null;
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "La clave y confirmación son diferentes", "Verifique la información suministrada"));
            return null;
        }
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getReTypePassword() {
        return reTypePassword;
    }

    public void setReTypePassword(String reTypePassword) {
        this.reTypePassword = reTypePassword;
    }

    public EntityManagerFactory getEmf() {
        return emf;
    }

    public void setEmf(EntityManagerFactory emf) {
        this.emf = emf;
    }

    public UserTransaction getUtx() {
        return utx;
    }

    public void setUtx(UserTransaction utx) {
        this.utx = utx;
    }

    public UsuacontJpaController getUsuacontJpaController() {
        return usuacontJpaController;
    }

    public void setUsuacontJpaController(UsuacontJpaController usuacontJpaController) {
        this.usuacontJpaController = usuacontJpaController;
    }

    public String getPasswordOld() {
        return passwordOld;
    }

    public void setPasswordOld(String passwordOld) {
        this.passwordOld = passwordOld;
    }

}
